<?php
/**
 * 微信红包管理
 */
namespace Common\Model;
use Think\Exception;

class RedpackModel extends BaseModel{
	static $instance=null;
	public static function getPackInstance(){
		if(!self::$instance){
			self::$instance=M('redpack_set',null,DB_MAIN_CFG);
		}
		return self::$instance;
	}

	static $waveInstance=null;
	public static function getWaveInstance(){
		if(!self::$waveInstance){
			self::$waveInstance=M('redpack_wave',null,DB_MAIN_CFG);
		}
		return self::$waveInstance;
	}


	static $recordInstance=null;
	public static function getRecordInstance(){
		if(!self::$recordInstance){
			self::$recordInstance=M('redpack_record',null,DB_MAIN_CFG);
		}
		return self::$recordInstance;
	}

	//红包抽奖获得类型
	const CHANCE_TYPE_ALL		= 0;//全部
	const CHANCE_TYPE_DEFAULT	= 1;//默认赠送
	const CHANCE_TYPE_SHARE		= 2;//分享获得

	const CHANCE_STATUS_UNUSED 	    =0;//默认未使用
	const CHANCE_STATUS_USED 		=1;//已使用

	const PRIZE_TYPE_MONEY 		=1;//现金红包
	const PRIZE_TYPE_POINT 		=2;//积分
	const PRIZE_TYPE_QUOTA 		=3;//名额
	const PRIZE_TYPE_THANKS 	=4;//谢谢参与

	const LIMIT_ZONE_NONE 		='NONE';//不限
	const LIMIT_ZONE_ZHEJIANG 	='ZHEJIANG';//限浙江
	const LIMIT_ZONE_NINGBO 	='NINGBO';//限宁波
	public static function getLimitZoneKV(){
		return array(
			self::LIMIT_ZONE_NONE=>'不限',
			self::LIMIT_ZONE_ZHEJIANG=>'限浙江',
			self::LIMIT_ZONE_NINGBO=>'限浙江宁波',
		);
	}
	public static function getLimitZoneUseKV(){
		return array(
			self::LIMIT_ZONE_ZHEJIANG=>'中国浙江省',
			self::LIMIT_ZONE_NINGBO=>'中国浙江省宁波市',
		);
	}


	const CHANCE_TIME_LIMIT		=2;//分享获得抽奖次数至多两次
	static $chanceInstance=null;
	public static function getChanceInstance(){
		if(!self::$chanceInstance){
			self::$chanceInstance=M('redpack_chance',null,DB_MAIN_CFG);
		}
		return self::$chanceInstance;
	}


	//红包操作状态
	const PACK_STATUS_ALL			=0;//全部
	const PACK_STATUS_ONLINE   		=1;//正常
	const PACK_STATUS_PAUSE   		=2;//暂停，下线状态


	public static function getPackStatus(){
		return array(
			self::PACK_STATUS_ALL			=>'全部',
			self::PACK_STATUS_ONLINE   		=>'正常',
			self::PACK_STATUS_PAUSE   		=>'暂停',
		);
	}



	/**
	 * 获取红包细分记录
	 * @param $beginTime 	开始时间戳
	 * @param $endTime 	结束时间戳
	 * @param $page
	 * @param $pageSize
	 * @param int $uid
	 * @param int $setId
	 * @return array
	 */
	public static function getRecordList($beginTime,$endTime,$page,$pageSize,$uid=0,$setId=0){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		$tradeM = self::getRecordInstance();

		$where='1';

		if ($uid>0){
			$where .=" and uid={$uid}";
		}

		if ($setId>0){
			$where .=" and setId={$setId}";
		}

		if($beginTime>0){
			$where .=" and sendTime >={$beginTime}";
		}
		if($endTime>0){
			$where .=" and sendTime <={$endTime}";
		}


		$where .=" and uid>0 and sendTime>0";


		$dataSuccess['total'] = $tradeM->where($where)->count();//获取数据总条数
		$dataSuccess['page'] = $page ? $page : 1;//返回当前页
		$dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
		$dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
		$offset=($dataSuccess['page']-1)*$pageSize;


		$exchangeList = $tradeM->where($where)
			->order('id desc')
			->limit($offset,$pageSize)
			->select();

		$dataSuccess['data']=$exchangeList;
		return $dataSuccess;
	}




	public static function getPrizeList($uid,$setId=0){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$tradeM = self::getRecordInstance();
		$where='1';
		if ($uid>0){
			$where .=" and uid={$uid}";
		}

		if ($setId>0){
			$where .=" and setId={$setId}";
		}

		$exchangeList = $tradeM->where($where)
			->order('id desc')
			->field('prizeType,money,prizeName,sendTime')
			->select();

		$dataSuccess['data']=$exchangeList;
		return $dataSuccess;
	}

	/**
	 * 获取红包活动列表数据的基础方法
	 * Author: shijy
	 * @param $packStatus 红包操作状态
	 * @param $page
	 * @param $pageSize
	 * @param int $uid 用户
	 * @return array
	 */
	public static function getList($packStatus,$page,$pageSize,$uid=0){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		$now_time=time();
		$pointMall = self::getPackInstance();

		$where='1';
		if ($packStatus != self::PACK_STATUS_ALL){
			$where .=" and `status`={$packStatus}";
		}


		$dataSuccess['total'] = $pointMall->where($where)->count();//获取数据总条数
		$dataSuccess['page'] = $page ? $page : 1;//返回当前页
		$dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
		$dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是否有下一页
		$offset=($dataSuccess['page']-1)*$pageSize;


		$exchangeList = $pointMall->where($where)
			->order('addTime desc')
			->limit($offset,$pageSize)
			->select();

		$dataSuccess['data']=$exchangeList;
		return $dataSuccess;
	}


	/**
	 * 获取红包活动键值
	 * @return array
	 */
	public static function getSetKV(){
		$list=self::getPackInstance()->getField('id,title',true);
		return $list;
	}


	/**
	 * 获取活动详情
	 * @param $packId
	 * @return mixed|null
	 */
	public static function getPackDetail($packId){
		$detail=self::getPackInstance()->where('id='.$packId)->find();

		if(!$detail) return null;
		$detail['wave']=self::getWaveInstance()->where('setId='.$packId)->select();

		return $detail;
	}


	/**
	 * 状态为暂停且发布量为0
	 * @param $packId
	 * @return bool
	 */
	public static function checkCanEdit($packId){
		return self::getPackInstance()->where("id={$packId} and issuedNum=0 and issuedMoney=0 and status=".self::PACK_STATUS_PAUSE)->count()>0;
	}


	public static function addChance($uid,$redpackId){ //限制时间段内获得数，

		$now=time();
		$packSet=self::getPackInstance()->where("id={$redpackId} and status=".self::PACK_STATUS_ONLINE)->find();
		if(!$packSet){
			return array('status'=>1,'msg'=>'新年红包派完啦!');
		}
		if ($now>$packSet['endTime']){
			return array('status'=>1,'msg'=>'新年红包派完啦!');
		}

		//进行中的波次
		$waveSet=self::getWaveInstance()->where("setId={$redpackId} and {$now} < endTime")->order('endTime asc')->limit(1)->find();
		if(!$waveSet){
			return array('status'=>2,'msg'=>'没有进行中的红包活动');
		}

		if(self::getChanceInstance()->where("setId={$redpackId} and uid='{$uid}' and type=".self::CHANCE_TYPE_SHARE)->count()>=self::CHANCE_TIME_LIMIT) {
			return array('status'=>2,'msg'=>'累计获奖次数已达上限，无法再获得！');
		}


		$lastWaveSet=self::getWaveInstance()->where("setId={$redpackId} and {$now} > beginTime")->order('beginTime desc')->limit(1)->find();
		$where="setId={$redpackId} and uid='{$uid}' and addTime<{$waveSet['endTime']} and type=".self::CHANCE_TYPE_SHARE;
		if($lastWaveSet){
			$where .=" and addTime>={$lastWaveSet['beginTime']}";
		}

		if(self::getChanceInstance()->where($where)->count()==0){
			self::getChanceInstance()->add(
				array('uid'=>$uid,
					'setId'=>$redpackId,
					'addTime'=>$now,
					'type'=>self::CHANCE_TYPE_SHARE,
					'status'=>self::CHANCE_STATUS_UNUSED)
			);
			$times=self::getChanceCount($uid,$redpackId,self::CHANCE_STATUS_UNUSED);
			return array('status'=>0,'msg'=>'获得一次抽红包机会','times'=>$times);
		}else{
			return array('status'=>2,'msg'=>'本场次已进行过分享，每场次分享只可获得1次抽奖机会。');
		}
	}

	public static function getChanceCount($uid,$redpackId,$status){
		return self::getChanceInstance()->where("uid={$uid} and setId={$redpackId} and status={$status}")->count();
	}




	/**
	 * 检查抽奖资格
	 * @param $uid
	 * @param $nickname
	 * @param $redpackId
	 * @return mixed|null
	 */
	public static function useChance($uid,$nickname,$redpackId){
		//判断是否已关注
		if (!UserModel::checkFollow($uid)) {
			return array('status' => 1, 'msg' => '请先关注公众号');
		}


		//红包活动判断
		$now=time();
		$packSet=self::getPackInstance()->where("id={$redpackId} and status=".self::PACK_STATUS_ONLINE)->find();
		if(!$packSet){
			return array('status'=>2,'msg'=>'新年红包派完啦，可持续关注丸子妈妈的其他活动福利哦！');
		}

		if($now>$packSet['endTime']){
			return array('status'=>5,'msg'=>'新年红包派完啦，可持续关注丸子妈妈的其他活动福利哦！');
		}

		//判断可用抽奖机会
		$chance=self::getChanceInstance()->where("uid={$uid} and setId={$redpackId} and status=".self::CHANCE_STATUS_UNUSED)->find();
		if(!$chance){
			return array('status'=>4,'msg'=>'分享本活动，即可获得1次抽红包机会');
		}





		$nextTime=self::getNextWaveBeginTime($redpackId);
		$waveSet=self::getWaveInstance()->where("setId={$redpackId} and {$now} between beginTime and endTime")->find();
		if(!$waveSet){
			if($now < $packSet['beginTime']){//整体活动未开始
				return array('status' => 2, 'msg' => "红包将于{$nextTime}开始派送");
			}else{
				return array('status' => 2, 'msg' => "下一场红包派送时间为{$nextTime}");
			}
		}




		//判断已参与次数
		$joinTimes=self::getChanceInstance()->where("uid='{$uid}' and setId={$redpackId} and useTime between {$waveSet['beginTime']} and {$waveSet['endTime']} and status=".self::CHANCE_STATUS_USED)->count();
		$joinTimesLimit=1;
		if($joinTimes >= $joinTimesLimit){
			if($nextTime===0){
				return array('status'=>3,'msg'=>"红包派送至最后1场啦，分享至朋友圈呼叫小伙伴，一起瓜分所有红包吧！");
			}else{
				return array('status'=>3,'msg'=>"您已抽取过本场红包，锁定下一场红包派送时间：{$nextTime}");
			}
		}


		$max=100000;
		$seed = rand(1,$max);
		$minNum = intval(0); $maxNum = intval(0);

		$prizeSetStr=explode("\r\n",$waveSet['waveSet']);
		$defaultprize=-1;
		$touch=-1;
		$waveSetArr=array();
		foreach ($prizeSetStr as $key=>$prizeSet) {
			$setArr		= explode(',',$prizeSet);
			$waveSetArr[]=$setArr;
			$rate		= $setArr[1];
			$prizeNum		= $setArr[2];
			if ($prizeNum<0){
				$defaultprize=$key;
			}

			if($key>0){$minNum = $maxNum;}
			$maxNum += $rate * $max;
			if($seed>$minNum && $seed <= $maxNum){//命中
				$touch=$key;
			}
		}
		$isHit=true;
		if ($touch<0 || $waveSetArr[$touch][2]==0){//不在概率内，或者奖品发放完了
			$touch=$defaultprize;
			if ($touch<0 || $waveSetArr[$touch][2]==0){//不在概率内，或者奖品发放完了
				$isHit=false;
			}
		}

		if (!$isHit){
			$result = 'success';
			$prizeName = '谢谢参与！';
			self::getChanceInstance()->where("id={$chance['id']}")->save(array('status' => 1, 'useTime' => $now));//使用抽奖机会
		}else {

			$prizeType = $waveSetArr[$touch][0];
			$prizeNum = $waveSetArr[$touch][2];


			if ($prizeType == RedpackModel::PRIZE_TYPE_MONEY) {
				//奖池判断
				$record = self::getRecordInstance()->where("setId={$redpackId} and waveId<={$waveSet['waveId']} and prizeIndex={$touch} and status =" . self::PACK_STATUS_ONLINE . ' and sendTime=0')->find();
				if (!$record) {
					if ($nextTime === 0) {
						return array('status' => 3, 'msg' => "红包派送至最后1场啦，分享至朋友圈呼叫小伙伴，一起瓜分所有红包吧！");
					} else {
						return array('status' => 3, 'msg' => "您已抽取过本场红包，锁定下一场红包派送时间：{$nextTime}");
					}
				}

				/**
				 * 发出红包
				 */
				self::getChanceInstance()->startTrans();

				//占位
				self::getRecordInstance()->where("id={$record['id']}")->setField('sendTime', 1);
				self::getChanceInstance()->where("id={$chance['id']}")->save(array('status' => 1, 'useTime' => $now));//使用抽奖机会

				$weixin = M('u_user_weixin', null, DB_MAIN_CFG)->where("uid ='{$uid}'")->field('WX_unionID,WX2_openID')->find();

				$result = WeixinRedPackModel::sendPack($weixin['WX2_openID'], $record['money'], $packSet['title'], $record['wish']);//微信推送红包
				self::getRecordInstance()->where("id={$record['id']}")->save(
					array('uid' => $uid, 'openId' => $weixin['WX2_openID'], 'nickname' => $nickname, 'sendTime' => $now, 'prizeName' => '红包', 'sendStatus' => $result)
				);
				self::getPackInstance()->where("id={$redpackId}")->save(
					array('issuedMoney' => $packSet['issuedMoney'] + $record['money'], 'issuedNum' => $packSet['issuedNum'] + 1)
				);
				self::getChanceInstance()->commit();
				if (strcasecmp('success', $result) == 0) {
					$prizeName = "获得：现金红包" . ($record['money'] / 100) . '元';
				}

			}
			elseif ($prizeType == RedpackModel::PRIZE_TYPE_POINT) {
				//奖池判断
				if ($prizeNum >= 0) {
					$count = self::getRecordInstance()->where("setId={$redpackId} and waveId<={$waveSet['waveId']} and prizeIndex={$touch} ")->count();
					if ($count >= $prizeNum) {
						if ($nextTime === 0) {
							return array('status' => 3, 'msg' => "红包派送至最后1场啦，分享至朋友圈呼叫小伙伴，一起瓜分所有红包吧！");
						} else {
							return array('status' => 3, 'msg' => "您已抽取过本场红包，锁定下一场红包派送时间：{$nextTime}");
						}
					}
				}


				self::getChanceInstance()->startTrans();

				$pointVal = rand($waveSetArr[$touch][3], $waveSetArr[$touch][4]);

				self::getChanceInstance()->where("id={$chance['id']}")->save(array('status' => 1, 'useTime' => $now));//使用抽奖机会
				self::getRecordInstance()->add(array('setId' => $redpackId, 'waveId' => $waveSet['waveId'], 'prizeIndex' => $touch, 'prizeType' => RedpackModel::PRIZE_TYPE_POINT, 'money' => $pointVal, 'uid' => $uid, 'nickname' => $nickname, 'sendTime' => $now));
				UserModel::plusPoint($uid, -1, $pointVal, OPT_TURN);
				self::getChanceInstance()->commit();
				$result = 'success';
				$prizeName = "获得：{$pointVal}积分";

			}
			elseif ($prizeType == RedpackModel::PRIZE_TYPE_QUOTA) {
				//奖池判断
				if ($prizeNum >= 0) {
					$count = self::getRecordInstance()->where("setId={$redpackId} and waveId<={$waveSet['waveId']} and prizeIndex={$touch} ")->count();
					if ($count >= $prizeNum) {
						if ($nextTime === 0) {
							return array('status' => 3, 'msg' => "红包派送至最后1场啦，分享至朋友圈呼叫小伙伴，一起瓜分所有红包吧！");
						} else {
							return array('status' => 3, 'msg' => "您已抽取过本场红包，锁定下一场红包派送时间：{$nextTime}");
						}
					}
				}

				self::getChanceInstance()->startTrans();
				$prizeName = $waveSetArr[$touch][3];
				self::getChanceInstance()->where("id={$chance['id']}")->save(array('status' => 1, 'useTime' => $now));//使用抽奖机会
				self::getRecordInstance()->add(array('setId' => $redpackId, 'waveId' => $waveSet['waveId'], 'prizeIndex' => $touch, 'prizeType' => RedpackModel::PRIZE_TYPE_QUOTA, 'money' => 0, 'prizeName' => $prizeName, 'uid' => $uid, 'nickname' => $nickname, 'sendTime' => $now));
				self::getChanceInstance()->commit();
				$result = 'success';
				$prizeName = '获得：' . $prizeName;
			}
			else {
				$result = 'success';
				$prizeName = '谢谢参与！';
				self::getChanceInstance()->where("id={$chance['id']}")->save(array('status' => 1, 'useTime' => $now));//使用抽奖机会
			}
		}


		if(strcasecmp('success',$result)==0) {
			$nextTime=self::getNextWaveBeginTime($redpackId);
			return array('status' => 0, 'msg' => $prizeName,'nextTime'=>$nextTime);
		}else{
			return array('status' => 6, 'msg' => $result);
		}
	}

	/**
	 * 获取下场次开始时间
	 * @param $redpackId
	 * @return int|string
	 */
	public static function getNextWaveBeginTime($redpackId){
		$now=time();
		$nextWaveBeginTime = self::getWaveInstance()->where("setId={$redpackId} and beginTime>={$now}")->min('beginTime');
		if(!$nextWaveBeginTime){
			$nextTime=0;//没有下一场
		}else{
			$timeStamp=$nextWaveBeginTime;
			$timeStr=sprintf('d-G-i',$timeStamp);
			$timeStr=date($timeStr,$timeStamp);
			list($day,$hour,$min)=explode('-',$timeStr);
			$nextTime=sprintf("%s日%s点",$day,$hour);
			$min +=0;
			if($min>0){
				$nextTime.=$min.'分';
			}
		}
		return $nextTime;
	}


}